package com.vcit.system.service.enroll.impl;

import com.vcit.common.core.domain.entity.SysDept;
import com.vcit.common.core.domain.entity.TStudent;
import com.vcit.common.exception.ServiceException;
import com.vcit.common.utils.DateUtils;
import com.vcit.common.utils.SecurityUtils;
import com.vcit.common.utils.StringUtils;
import com.vcit.common.utils.bean.BeanUtils;
import com.vcit.system.domain.clazz.TClazz;
import com.vcit.system.domain.clazz.TClazzStudent;
import com.vcit.system.domain.major.TMajor;
import com.vcit.system.domain.student.StudentDTO;
import com.vcit.system.domain.vo.EnrollStudentVo;
import com.vcit.system.mapper.SysDeptMapper;
import com.vcit.system.mapper.SysRoleMapper;
import com.vcit.system.mapper.clazz.TClazzMapper;
import com.vcit.system.mapper.clazz.TClazzStudentMapper;
import com.vcit.system.mapper.enroll.EnrollMapper;
import com.vcit.system.mapper.major.TMajorMapper;
import com.vcit.system.mapper.student.TStudentMapper;
import com.vcit.system.service.enroll.EnrollService;
import com.vcit.system.service.impl.SysUserServiceImpl;
import com.vcit.system.util.StudentNumberGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 学生招生Service业务层处理
 *
 * @author dff
 * @date 2025-04-28
 */
@Service
public class EnrollServiceImpl  implements EnrollService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private EnrollMapper enrollMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private TMajorMapper majorMapper;

    @Autowired
    private StudentNumberGenerator studentNumberGenerator;
    @Autowired
    private TClazzMapper tClazzMapper;
    @Autowired
    private TClazzStudentMapper tClazzStudentMapper;
    @Autowired
    private TStudentMapper tStudentMapper;


    /**
     * 查询学生招生
     *
     * @param id 学生招生主键
     * @return 学生招生
     */
    @Override
    public EnrollStudentVo selectZhaoshengStudentById(Long id)
    {
        return enrollMapper.selectZhaoshengStudentById(id);
    }

    /**
     * 查询学生招生列表
     *
     * @param zhaoshengStudent 学生招生
     * @return 学生招生
     */
    @Override
    public List<EnrollStudentVo> selectZhaoshengStudentList(EnrollStudentVo zhaoshengStudent)
    {
        List<EnrollStudentVo>  studentVoList =   enrollMapper.selectZhaoshengStudentList(zhaoshengStudent);



        return studentVoList;
    }

    /**
     * 新增学生招生
     *
     * @param zhaoshengStudent 学生招生
     * @return 结果
     */
    @Override
    public int insertZhaoshengStudent(EnrollStudentVo zhaoshengStudent)
    {
        // 获取学号
       String sno = generatorStudentSno(zhaoshengStudent);
       zhaoshengStudent.setSno(sno);
        zhaoshengStudent.setCreateTime(DateUtils.getNowDate());
        return enrollMapper.insertZhaoshengStudent(zhaoshengStudent);
    }

    private String generatorStudentSno(EnrollStudentVo  student) {

        // 如果学号为空，则生成新的学号
        if (StringUtils.isEmpty(student.getSno())) {
            String majorCode = String.format("%03d", student.getMajorId()); // 使用专业ID作为专业代码
           return studentNumberGenerator.generateStudentNumber(student.getZsYear(), majorCode,student.getStudentType());
        }else {
            throw  new ServiceException("zhao sheng xue sheng xinzeng  sno  cuowu "+student.getStudentName());
        }
    }


    /**
     * 修改学生招生
     *
     * @param zhaoshengStudent 学生招生
     * @return 结果
     */
    @Override
    public int updateZhaoshengStudent(EnrollStudentVo zhaoshengStudent)
    {
        return enrollMapper.updateZhaoshengStudent(zhaoshengStudent);
    }

    /**
     * 批量删除学生招生
     *
     * @param ids 需要删除的学生招生主键
     * @return 结果
     */
    @Override
    public int deleteZhaoshengStudentByIds(Long[] ids)
    {
        return enrollMapper.deleteZhaoshengStudentByIds(ids);
    }

    /**
     * 删除学生招生信息
     *
     * @param id 学生招生主键
     * @return 结果
     */
    @Override
    public int deleteZhaoshengStudentById(Long id)
    {
        return enrollMapper.deleteZhaoshengStudentById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importZhaoshengStudent(List<EnrollStudentVo> studentList, String operName,boolean updateSupport) {
        if (StringUtils.isNull(studentList) || studentList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (EnrollStudentVo student : studentList) {

            // 按照专业名   找系部id 找专业id

            TMajor major= new TMajor();
            major.setMajorName(student.getMajorName());
            List<TMajor> majorList = majorMapper.selectTMajorList(major);
            student.setMajorId(majorList.get(0).getId());

            SysDept dept = new SysDept();
            dept.setDeptName(student.getDeptName());
            List<SysDept> listDept = sysDeptMapper.selectDeptList(dept);
            student.setDeptId(listDept.get(0).getDeptId());



            try {
                // 验证是否存在这个学生
                EnrollStudentVo existStudent = enrollMapper.selectZhaoshengStudentByNameAndIdCard(student.getStudentName(),student.getIdCard());
                if (StringUtils.isNull(existStudent)) {
                    // 不存在则插入
                    student.setCreateBy(operName);
                    student.setZsYear(LocalDate.now().getYear()+"");
                    this.insertZhaoshengStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getStudentName() + " 导入成功");
                } else if (updateSupport){
                    // 存在则更新
                    student.setUpdateBy(operName);
                    student.setSno(existStudent.getSno());
                    student.setId(existStudent.getId());
                    student.setZsYear(LocalDate.now().getYear()+"");
                    this.updateZhaoshengStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + student.getStudentName() + " 更新成功");
                }
            } catch (Exception e) {

                failureNum++;
                String msg = "<br/>" + failureNum + "、学生 " + student.getStudentName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                throw  new ServiceException(e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int assignClassToStudent(StudentDTO studentDTO) {
        // 1. 校验学生是否存在
        EnrollStudentVo student = enrollMapper.selectZhaoshengStudentById(studentDTO.getId());
        if (student == null) {
            throw new ServiceException("学生不存在");
        }
        // 2. 校验招生状态
        if (student.getZsStatus() == null ||
                !(student.getZsStatus() == 6 || student.getZsStatus() == 7)) {
            throw new ServiceException("只有招生状态为已录取或已确认入学的学生才能分配班级");
        }
        // 3. 校验班级是否存在
        TClazz clazz = tClazzMapper.selectTClazzById(studentDTO.getClazzId());
        if (clazz == null) {
            throw new ServiceException("班级不存在");
        }
        // 4. 校验学生是否已分配班级
        TClazzStudent clazzStudent = tClazzStudentMapper.selectTClazzStudentByStudentId(studentDTO.getId());
        if (clazzStudent !=null && clazzStudent.getClazzId() != null && clazzStudent.getClazzId().equals(studentDTO.getClazzId())) {
            throw new ServiceException("该学生已分配到该班级");
        }


        //更新学生在读状态
        TStudent stu = new TStudent();
        BeanUtils.copyProperties(student,stu);
        stu.setStatus(1);//在读
        stu.setZsStatus(8);//已分班
        stu.setUpdateTime(DateUtils.getNowDate());
        stu.setUpdateBy(studentDTO.getUpdateBy());
        tStudentMapper.updateTStudent(stu);//更新学生状态
        clazzStudent = new TClazzStudent();
        BeanUtils.copyProperties(student,clazzStudent);
        BeanUtils.copyProperties(stu,clazzStudent);

        clazzStudent.setCreateTime(DateUtils.getNowDate());//班级分配时间
        clazzStudent.setCreateBy(SecurityUtils.getUsername());
        clazzStudent.setClazzId(studentDTO.getClazzId());
        clazzStudent.setStudentId(studentDTO.getId());
        clazzStudent.setId(null);
        int result = tClazzStudentMapper.insertTClazzStudent(clazzStudent);

        if (result == 0) {
            throw new ServiceException("分配班级失败");
        }
        return result;
    }
}